#!/bin/bash

# 设置环境变量
export UESTUDIO="/d/vc/UEStudio"
export UESTUDIO_SRC="$UESTUDIO/src"
export wxWIN="/d/vc/wxWidgets-3.2.7"
export wxINCLUDE="$wxWIN/include"
export wxSETUP_H="$wxWIN/lib/wx/include/msw-unicode-3.2"
export wxLIB_DLL="$wxWIN/lib"

export CXXFLAGS="-I. -I$UESTUDIO_SRC/include -I$UESTUDIO_SRC/sdk/wxscintilla/include -I$wxINCLUDE -I$wxSETUP_H -D__WXMSW__ -DcbDEBUG -DWXUSINGDLL -std=c++17"
export LDFLAGS="-L$wxLIB_DLL -L$UESTUDIO_SRC/devel"

echo "🚀 AICoder 插件编译开始..."
echo "=========================================="

# 清理旧文件
echo "清理旧编译文件..."
find . -name "*.o" -delete
rm -f AICoder.dll

# 编译函数
compile_file() {
    local file=$1
    echo "编译: $file"
    if g++ $CXXFLAGS -c "$file" -o "${file%.cpp}.o"; then
        echo "✅ $file 编译成功"
        return 0
    else
        echo "❌ $file 编译失败"
        return 1
    fi
}

# 编译所有源文件
echo "步骤1: 编译协作框架..."
compile_file "CollaborativeCore/CollaborationProtocol.cpp" || exit 1
compile_file "CollaborativeCore/RealTimeEditor.cpp" || exit 1
compile_file "ModelModuleSystem/ModelComponent.cpp" || exit 1
compile_file "ModelModuleSystem/ComponentAssembler.cpp" || exit 1
compile_file "GlobalRegistry/ComponentRegistry.cpp" || exit 1

echo "步骤2: 编译主插件..."
compile_file "AICoder.cpp" || exit 1

echo "步骤3: 链接生成DLL..."
if g++ -shared -o AICoder.dll \
    CollaborativeCore/*.o \
    ModelModuleSystem/*.o \
    GlobalRegistry/*.o \
    AICoder.o \
    $LDFLAGS \
    -lcodeblocks -lwx_mswu_core-3.2 -lwx_baseu-3.2; then
    
    echo "✅ AICoder.dll 链接成功！"
    echo "文件信息:"
    ls -lh AICoder.dll
    
    # 尝试部署
    echo "步骤4: 部署插件..."
    if cp AICoder.dll "$UESTUDIO/output/plugins/" 2>/dev/null; then
        echo "✅ 插件已部署到 $UESTUDIO/output/plugins/"
    else
        echo "⚠️  自动部署失败，请手动复制 AICoder.dll 到插件目录"
    fi
    
else
    echo "❌ 链接失败，尝试简化链接..."
    if g++ -shared -o AICoder.dll *.o $LDFLAGS -lcodeblocks; then
        echo "✅ AICoder.dll 简化链接成功！"
        ls -lh AICoder.dll
    else
        echo "❌ 所有链接尝试都失败了"
        exit 1
    fi
fi

echo "=========================================="
echo "🎉 AICoder 插件编译完成！"
